package com.hoperun.checkcloth.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.res.ResourcesCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hoperun.checkcloth.R;
import com.hoperun.checkcloth.adapter.StuffSJZDAdapter;
import com.hoperun.checkcloth.adapter.StuffXcslAdapter;
import com.hoperun.checkcloth.base.MIP_BaseActivity;
import com.hoperun.checkcloth.entity.MaterialEntity;
import com.hoperun.checkcloth.entity.XiaciInfo;
import com.hoperun.checkcloth.fragment.CountDialogFragmentV2;
import com.hoperun.checkcloth.fragment.StuffCountDialogFragment;
import com.hoperun.checkcloth.net.IServiceImpl;
import com.hoperun.checkcloth.net.RequestServiceImpl;
import com.hoperun.checkcloth.ui.StuffCheckInfoActivity;
import com.hoperun.checkcloth.util.SharedPreUtil;
import com.hoperun.checkcloth.view.SimpleDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.disposables.CompositeDisposable;

import static com.blankj.utilcode.util.KeyboardUtils.hideSoftInput;

public class StuffCheckMainActivity extends MIP_BaseActivity implements View.OnClickListener {

    /**
     * 查询词典类型的数据字典id
     **/
    private static final String SJZDID_TASKLX = "BADLX";
    private final static int REQUEST_CODE_MATERIAL_ACTIVITY = 1;

    private EditText monadNoEt;
    private TextView userNameTv;
    private EditText buhaoEt;
    private EditText pihaoEt;
    private EditText addressEt;
    private EditText pizhongEt;
    private EditText shazhiEt;
    private EditText sehaoEt;
    private ListView listView;
    private GridView xclxGridview;
    private Button xclxBtn;
    private Button bzBtn;
    private Button okBtn;
    private Button backBtn;
    private Button chooseBtn;
    /**
     * 瑕疵类型适配器
     **/
    private StuffSJZDAdapter flawInfoAdapter;
    /**
     * 瑕疵数量适配器
     **/
    private StuffXcslAdapter flawInfoNumAdapter;
    /**
     * 所有瑕疵类型
     **/
    final private List<XiaciInfo> mFlawList = new ArrayList<>();

    /**
     * 备注
     **/
    final private List<XiaciInfo> mbzList = new ArrayList<>();

    /**
     * 实际需要显示的数据
     **/
    final private List<XiaciInfo> mList = new ArrayList<>();
    /**
     * 瑕疵信息集合
     **/
    final private List<XiaciInfo> mFlawNumberList = new ArrayList<>();


    MaterialEntity mMaterialEntity = new MaterialEntity();
    /**
     * 三联单号是否正确
     **/
    private boolean isMonadNoCorrect = false;

    /**
     * 匹数
     **/
    private int mPsSum = 0;
    String mUserBean = "";

    private final List<MaterialEntity> mMaterialList = new ArrayList<>();

    /**
     * 单位
     */
    List<XiaciInfo> mUnitList = new ArrayList<>();

    final private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stuff_checking_activity);
        initViews();
        initEvent();
        initDate();
    }


    private void initDate() {
        mUserBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN,
                "");

        String username = (String) SharedPreUtil.getValue(this, SharedPreUtil.XM,
                "");
        userNameTv.setText(username);

        getDc();
        getDcs();
    }


    private void initViews() {
        userNameTv = findViewById(R.id.usernameTv);
        monadNoEt = findViewById(R.id.monadNoEt);
        buhaoEt = findViewById(R.id.buhaoEt);
        pihaoEt = findViewById(R.id.batchNoEt);
        addressEt = findViewById(R.id.addressEt);
        pizhongEt = findViewById(R.id.pizhongEt);
        shazhiEt = findViewById(R.id.shazhiEt);
        sehaoEt = findViewById(R.id.sehaoEt);
        listView = findViewById(R.id.xcListView);
        xclxBtn = findViewById(R.id.xclxBtn);
        bzBtn = findViewById(R.id.bzBtn);
        okBtn = findViewById(R.id.okBtn);
        backBtn = findViewById(R.id.backBtn);
        chooseBtn = findViewById(R.id.chooseBtn);
        xclxGridview = findViewById(R.id.xclxGridView);

        //计算布局实际高度
        ViewTreeObserver vto = xclxGridview.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                xclxGridview.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
                flawInfoAdapter.notifyDataSetChanged();
            }
        });

        flawInfoAdapter = new StuffSJZDAdapter(this, mList);
        xclxGridview.setAdapter(flawInfoAdapter);

        flawInfoNumAdapter = new StuffXcslAdapter(this, mFlawNumberList);
        listView.setAdapter(flawInfoNumAdapter);

        try {
            mPsSum = Integer.parseInt((String) SharedPreUtil.getValue(this,
                    SharedPreUtil.DATASUM, ""));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initEvent() {
        xclxBtn.setOnClickListener(this);
        bzBtn.setOnClickListener(this);
        okBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        chooseBtn.setOnClickListener(this);

        flawInfoAdapter.setOnBtnClickListener(position -> {
            XiaciInfo entity = mList.get(position);
            if (entity != null) {
                for (int i = 0; i < mFlawNumberList.size(); i++) {
                    XiaciInfo XiaCiInfo = mFlawNumberList.get(i);
                    if (XiaCiInfo.getKEYCODE().equals(entity.getKEYCODE())) {
                        mFlawNumberList.get(i).setXCSL("1");
                        flawInfoNumAdapter.notifyDataSetChanged();
                        return;
                    }
                }

                //如果列表中不存在，添加一条记录到疵点信息列表中,默认数量为1
                entity.setXCSL("1");
                mFlawNumberList.add(0, entity);
                flawInfoNumAdapter.notifyDataSetChanged();
            }
        });

        flawInfoNumAdapter.setOnDeleteClickListener(position -> {
            // 删除一条记录
            mFlawNumberList.remove(position);
            flawInfoNumAdapter.notifyDataSetChanged();
        });

        flawInfoNumAdapter.setOnCounterClickListener(position -> {
            //正常智能输入数字的对话框
            if (mFlawNumberList.get(position).getSJXZ().equals("0")) {
                String result = mFlawNumberList.get(position).getXCSL();
                final StuffCountDialogFragment dialog = StuffCountDialogFragment.newInstance(result);
                dialog.show(getSupportFragmentManager(), "CountDialog");
                dialog.setOnOKClickListener(result1 -> {
                    mFlawNumberList.get(position).setXCSL(result1);
                    flawInfoNumAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                });
            } else {

                //可以输入单位文字的对话框
                final CountDialogFragmentV2 dialog = CountDialogFragmentV2.newInstance(mFlawNumberList.get(position).getXCSL(), mUnitList);

                dialog.show(getSupportFragmentManager(), "CountDialog2");
                dialog.setOnOKClickListenerV2(result -> {
                    mFlawNumberList.get(position).setXCSL(result);
                    flawInfoNumAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                });
            }
        });

        monadNoEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                isMonadNoCorrect = false;// 三联号改变了需要重新校验
                mMaterialEntity = new MaterialEntity();
                buhaoEt.setText("");
                pihaoEt.setText("");
                addressEt.setText("");
                pizhongEt.setText("");
                shazhiEt.setText("");
                sehaoEt.setText("");
                mFlawNumberList.clear();
                flawInfoNumAdapter.notifyDataSetChanged();
            }
        });
        monadNoEt.setOnEditorActionListener((v, actionId, event) -> {
            if (event != null) {
                boolean case1 = event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP;
                boolean case2 = event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN;
                boolean case3 = actionId == EditorInfo.IME_ACTION_DONE;
                if (case1 | case2 | case3) {
                    hideSoftInput(monadNoEt);
                    return true;
                }
            }
            return false;
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.xclxBtn:
                mList.clear();
                mList.addAll(mFlawList);
                flawInfoAdapter.notifyDataSetChanged();
                xclxBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_blue_light, null));
                xclxBtn.setTextColor(this.getResources().getColor(R.color.white));
                bzBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_gray, null));
                bzBtn.setTextColor(this.getResources().getColor(R.color.black));
                break;
            case R.id.bzBtn:
                mList.clear();
                mList.addAll(mbzList);
                flawInfoAdapter.notifyDataSetChanged();
                xclxBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_gray, null));
                xclxBtn.setTextColor(this.getResources().getColor(R.color.black));
                bzBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_blue_light, null));
                bzBtn.setTextColor(this.getResources().getColor(R.color.white));
                break;
            case R.id.okBtn:
                String monadNo = monadNoEt.getText().toString().trim();
                if (TextUtils.isEmpty(monadNo)) {
                    SimpleDialog.show(this, "请扫描三联单号！");
                    return;
                } else if (!isMonadNoCorrect) {
                    SimpleDialog.show(this, "三联单号校验不成功，请重新输入，查询后再试！");
                    return;
                }
                commit(mMaterialEntity, mFlawNumberList);
                break;
            case R.id.chooseBtn:
                String ClothTktNo = monadNoEt.getText().toString().trim();
                if (TextUtils.isEmpty(ClothTktNo)) {
                    Toast.makeText(this, "请输入三联单号后再试！", Toast.LENGTH_SHORT).show();
                    return;
                }
                queryYlzlByClothTktNo(ClothTktNo);
                break;
            case R.id.backBtn:
                this.finish();
                break;
            default:
                break;
        }
    }


    // 为了获取结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_MATERIAL_ACTIVITY) {
                MaterialEntity entity = (MaterialEntity) data.getExtras().getSerializable("material");

                if (entity != null) {

                    buhaoEt.setText(entity.getCLOTHNO());
                    pihaoEt.setText(entity.getBATCHNO());
                    addressEt.setText(entity.getORIPLACE());
                    pizhongEt.setText(String.valueOf(entity.getWEIGHT()));
                    shazhiEt.setText(entity.getSZQC());
                    sehaoEt.setText(entity.getCOLORNO());

                    mMaterialEntity = entity;
                    String monadNo = monadNoEt.getText().toString().trim();
                    queryByMonadNo(monadNo, entity.getYLWZ());
                }
            }
        }
    }


    /**
     * 获取所有瑕疵信息
     */
    private void getDc() {
        showWait();
        RequestServiceImpl.getDc(mMIPHandler, IServiceImpl.TYPE_GETDC);
    }


    /***
     * 获取单位
     */
    private void getDcs() {
        showWait();
        RequestServiceImpl.getDcs(mMIPHandler, IServiceImpl.TYPE_GETDCS);
    }


    /**
     * 根据三联号获取相关原料信息
     */
    private void queryYlzlByClothTktNo(String monadNo) {
        showWait();
        RequestServiceImpl.getYlzlCheckListInfo(mMIPHandler, IServiceImpl.TYPE_getYlzlCheckListInfo, monadNo, mUserBean);
    }


    /**
     * 查询已经保存的数据
     */
    private void queryByMonadNo(String monadNo, String ylwz) {
        showWait();
        RequestServiceImpl.getYlzllrUpdateInfo(mMIPHandler, IServiceImpl.TYPE_getYlzllrUpdateInfo, monadNo, ylwz);

    }

    /**
     * 提交瑕疵接口
     */
    private void commit(MaterialEntity cloth, List<XiaciInfo> flawList) {
        showWait();
        RequestServiceImpl.saveOrUpdateYlzllr(mMIPHandler,
                IServiceImpl.TYPE_saveOrUpdateYlzllr, cloth, flawList, mUserBean);
    }


    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) {
        stopWait();
        if (error) {
            switch (requestType) {
                case IServiceImpl.TYPE_GETDC:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        JSONArray normalJsonArray = jsonObj.optJSONArray("NOMCOLUMS");
                        JSONArray remarkJsonArray = jsonObj.optJSONArray("REMARKCOLUMS");
                        Gson gson = new Gson();
                        List<XiaciInfo> normalList = gson.fromJson(
                                normalJsonArray.toString(),
                                new TypeToken<List<XiaciInfo>>() {
                                }.getType());
                        List<XiaciInfo> remarkList = gson.fromJson(
                                remarkJsonArray.toString(),
                                new TypeToken<List<XiaciInfo>>() {
                                }.getType());
                        mFlawList.addAll(normalList);
                        mbzList.addAll(remarkList);
                        mList.addAll(mFlawList);
                        flawInfoAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, "查询数据字典失败！");
                    }
                    break;
                case IServiceImpl.TYPE_GETDCS:
                    try {
                        JSONArray jsonArray = new JSONArray((String) objBody);
                        Gson gson = new Gson();
                        List<XiaciInfo> list = gson.fromJson(
                                jsonArray.toString(),
                                new TypeToken<List<XiaciInfo>>() {
                                }.getType());
                        mUnitList.addAll(list);
                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, "查询数据字典失败！");
                    }
                    break;

                case IServiceImpl.TYPE_getYlzllrUpdateInfo:
                    try {
                        isMonadNoCorrect = true;// 查询成功
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        Gson gson = new Gson();
                        MaterialEntity entity = gson.fromJson(jsonObj.toString(),
                                MaterialEntity.class);
                        if (entity != null && !TextUtils.isEmpty(entity.getPKID())) {
                            mMaterialEntity = entity;
                        }
                        JSONArray jsonArray = jsonObj.optJSONArray("DATALIST");
                        if (jsonArray != null) {
                            List<XiaciInfo> flawList = gson.fromJson(
                                    jsonArray.toString(),
                                    new TypeToken<List<XiaciInfo>>() {
                                    }.getType());
                            mFlawNumberList.clear();
                            if (flawList != null) {
                                mFlawNumberList.addAll(flawList);

                            }
                            flawInfoNumAdapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, "查询失败！");
                    }
                    break;
                case IServiceImpl.TYPE_saveOrUpdateYlzllr:
                    try {
                        SimpleDialog.show(this, (String) objBody);
                        monadNoEt.setText("");
                        mMaterialEntity = null;
                        buhaoEt.setText("");
                        pihaoEt.setText("");
                        addressEt.setText("");
                        pizhongEt.setText("");
                        shazhiEt.setText("");
                        sehaoEt.setText("");
                        mFlawNumberList.clear();
                        flawInfoNumAdapter.notifyDataSetChanged();
                        monadNoEt.requestFocus();
                        mPsSum++;
                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, "录入失败！");
                    }
                    break;
                case IServiceImpl.TYPE_getYlzlCheckListInfo:
                    try {
                        Gson gson = new Gson();
                        List<MaterialEntity> list = gson.fromJson(
                                objBody.toString(),
                                new TypeToken<List<MaterialEntity>>() {
                                }.getType());

                        mMaterialList.clear();
                        mMaterialList.addAll(list);
                        if (mMaterialList.size() > 0) {
                            Intent intent = new Intent(this, StuffCheckInfoActivity.class);
                            intent.putExtra("materialList", (Serializable) mMaterialList);
                            startActivityForResult(intent, REQUEST_CODE_MATERIAL_ACTIVITY);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, "查询原料信息失败！");
                    }
                    break;
            }
        } else {
            if (objBody != null) {
                String obj = objBody.toString();
                SimpleDialog.show(this, obj);
            }

        }

    }


}
